package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrdersService;
import com.sky.utils.BeanCopyUtils;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author MrWang
* @description 针对表【orders(订单表)】的数据库操作Service实现
* @createDate 2023-10-26 13:35:04
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    //用户下单
    @Transactional
    @Override
    public Result saveOrders(OrdersSubmitDTO ordersSubmitDTO) {

        //1.地址簿为空 购物车为空 都不能下单
        Orders orders = BeanCopyUtils.copyBean(ordersSubmitDTO, Orders.class);
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);//地址为空 无法下单
        }

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(queryWrapper);
        if (shoppingCarts == null || shoppingCarts.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);//购物车为空 无法下单
        }

        //2.向订单表插入一条数据
        orders.setNumber(String.valueOf(System.currentTimeMillis())); //订单号
        orders.setStatus(Orders.PENDING_PAYMENT); //订单状态 1 待付款状态
        orders.setUserId(BaseContext.getCurrentId()); //下单用户id
//        orders.setOrderTime(new Date(System.currentTimeMillis()+8*60*60*1000));//时差8小时 System.currentTimeMillis()+8*60*60*1000
        orders.setOrderTime(new Date());
        orders.setPayStatus(Orders.UN_PAID); //支付状态 未支付
        orders.setPhone(addressBook.getPhone()); //电话号码
        orders.setAddress(addressBook.getDetail()); ////地址
        orders.setConsignee(addressBook.getConsignee()); //收货人
        User user = userMapper.selectById(orders.getUserId());
        orders.setUserName(user.getName()); ////用户名

        ordersMapper.insert(orders);

        //3.向订单详情表插入n条数据
        List<OrderDetail> orderDetails = BeanCopyUtils.copyBeanList(shoppingCarts, OrderDetail.class);
        orderDetails.stream().map(orderDetail -> {
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.insert(orderDetail);
            return orderDetail;
        }).collect(Collectors.toList());

        //4.清空当前购物车数据
        shoppingCartMapper.delete(queryWrapper);

        //5.封装返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return Result.success(orderSubmitVO);
    }

    //支付
    @Transactional
    @Override
    public Result payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return Result.success(vo);
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Transactional
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询当前用户的订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getNumber,outTradeNo);
        Orders ordersDB = ordersMapper.selectOne(queryWrapper);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(new Date());

        ordersMapper.updateById(orders);
    }


    //查询历史订单
    @Transactional
    @Override
    public Result ordersList(String page,String pageSize, String status) {
        //1.先查看订单列表
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(StringUtils.hasText(status),Orders::getStatus,status)
                .eq(Orders::getUserId,BaseContext.getCurrentId())
                .orderByDesc(Orders::getOrderTime);//最新的订单在前面
        Page<Orders> page1 = new Page<>(Long.valueOf(page),Long.valueOf(pageSize));
        ordersMapper.selectPage(page1,queryWrapper);
        List<Orders> ordersList = page1.getRecords();
        List<OrderVO> orderVOS = BeanCopyUtils.copyBeanList(ordersList, OrderVO.class);
        //2.给每个订单的细则列表赋值
        orderVOS.stream().map(orderVO -> {
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<OrderDetail>()
                    .eq(OrderDetail::getOrderId,orderVO.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper1);
            orderVO.setOrderDetailList(orderDetails);
            return orderVO;
        }).collect(Collectors.toList());

        return Result.success(new PageResult(page1.getTotal(), orderVOS));
    }

    //查看订单详情
    @Transactional
    @Override
    public Result getOrdersDetailById(String id) {
        //1.先查看订单信息
        Orders orders = ordersMapper.selectById(id);
        //2.查看订单细则
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
        //封装
        OrderVO orderVO = BeanCopyUtils.copyBean(orders, OrderVO.class);
        orderVO.setOrderDetailList(orderDetails);
        return Result.success(orderVO);
    }

    //取消订单
    @Transactional
    @Override
    public Result cancel(String id) {
        //1.查看订单 状态
        Orders orders = ordersMapper.selectById(id);
        if (orders == null){//订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() > 2){//无法取消
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders1 = new Orders();
        orders1.setId(orders.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
            //支付状态修改为 退款
            orders1.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason("用户取消");
        orders1.setCancelTime(new Date());
        ordersMapper.updateById(orders1);
        return Result.success();
    }

    //再来一单
    @Override
    public Result repetition(String id) {
        Long userId = BaseContext.getCurrentId();
        //1.查询订单细则列表
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(queryWrapper);
        //2.将订单细则转化为购物车对象 并插入购物车表
        orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = BeanCopyUtils.copyBean(orderDetail, ShoppingCart.class);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(new Date());
            shoppingCartMapper.insert(shoppingCart);
            return shoppingCart;
        }).collect(Collectors.toList());
        return Result.success();
    }


    //管理端
    //订单搜索
    @Override
    public Result conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        LocalDateTime beginTime = ordersPageQueryDTO.getBeginTime();
        LocalDateTime endTime = ordersPageQueryDTO.getEndTime();
        String number = ordersPageQueryDTO.getNumber();
        String phone = ordersPageQueryDTO.getPhone();
        Integer status = ordersPageQueryDTO.getStatus();

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .ge(Objects.nonNull(beginTime),Orders::getOrderTime,beginTime)
                .le(Objects.nonNull(endTime),Orders::getOrderTime,endTime)
                .like(StringUtils.hasText(number),Orders::getNumber,number)
                .like(StringUtils.hasText(phone),Orders::getPhone,phone)
                .eq(Objects.nonNull(status),Orders::getStatus,status);
        Page<Orders> page = new Page(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        ordersMapper.selectPage(page,queryWrapper);
        List<Orders> ordersList = page.getRecords();
        //VO
        List<OrderVO> orderVOS = BeanCopyUtils.copyBeanList(ordersList, OrderVO.class);

        //给每个订单的ordersDishes赋值
        orderVOS.stream().map(orderVO -> {
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<OrderDetail>()
                    .eq(OrderDetail::getOrderId,orderVO.getId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(queryWrapper1);
            orderVO.setOrderDishes(orderDetailList.toString());
            return orderVO;
        }).collect(Collectors.toList());
        System.out.println(orderVOS);

        return Result.success(new PageResult(page.getTotal(), orderVOS));
    }

    //查看订单详情
    @Override
    public Result getOrdersDetails(String id) {
        //1.查看订单信息
        Orders orders = ordersMapper.selectById(id);
        //2.查看订单细则列表
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(queryWrapper);
        //VO
        OrderVO orderVO = BeanCopyUtils.copyBean(orders, OrderVO.class);
        orderVO.setOrderDetailList(orderDetailList);

        return Result.success(orderVO);
    }

    //各个状态的订单数量统计 订单状态 1待付款 ( 2待接单 3已接单 4派送中 ) 5已完成 6已取消 7退款
    @Override
    public Result statistics() {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.TO_BE_CONFIRMED);//待接单 2;
        Integer toBeConfirmed = ordersMapper.selectCount(queryWrapper);
        LambdaQueryWrapper<Orders> queryWrapper2 = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.CONFIRMED);// 已接单/待派送 3
        Integer confirmed = ordersMapper.selectCount(queryWrapper2);
        LambdaQueryWrapper<Orders> queryWrapper3 = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.DELIVERY_IN_PROGRESS);// 派送中 4
        Integer deliveryInProgress = ordersMapper.selectCount(queryWrapper3);

        //VO
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        System.out.println("=========================");
        System.out.println(orderStatisticsVO);
        return Result.success(orderStatisticsVO);
    }

    //接单
    @Override
    public Result confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);// status 已接单 3
        ordersMapper.updateById(orders);
        return Result.success();
    }

    //拒单
    @Override
    public Result rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //查询该订单
        Orders ordersDB = ordersMapper.selectById(ordersRejectionDTO.getId());
        //判断订单状态是否为待接单状态 只有待接单状态才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //退款
        if (ordersDB.getPayStatus() == Orders.PAID){
            //退款
            System.out.println("====================微信退款====================");
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(new Date());
        orders.setPayStatus(Orders.REFUND);//退款后更新pay_status为 2 已退款状态
        ordersMapper.updateById(orders);
        return Result.success();
    }

    //admin 取消订单
    @Override
    public Result cancelByAdmin(OrdersCancelDTO ordersCancelDTO) {
        //查询订单
        Orders orders = ordersMapper.selectById(ordersCancelDTO.getId());
        //如果已支付 就要退款 并修改pay_status为已退款
        if (orders.getPayStatus() == Orders.PAID){
            System.out.println("===========admin申请下该订单=============");
        }
        //更新订单信息
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(new Date());
        orders.setPayStatus(Orders.REFUND);//pay_status为已退款
        ordersMapper.updateById(orders);
        return Result.success();
    }

    //派送订单
    @Override
    public Result deliveryOrders(String id) {
        //查询订单信息
        Orders orders = ordersMapper.selectById(id);
        //判断订单是否存在 是否是已接单状态 3
        if (orders == null || !orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新该订单状态为 派送中 4
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.updateById(orders);
        return Result.success();
    }

    //完成订单
    @Override
    public Result completeOrders(String id) {
        //查看订单信息
        Orders orders = ordersMapper.selectById(id);
        //判断该订单是否存在 是否为派送中 4 状态
        if (orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新订单状态为完成 5 完成时间
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(new Date());
        ordersMapper.updateById(orders);
        return Result.success();
    }


}




